package com.zookeeper.demo;

import com.zookeeper.utils.ConnectionUtil;
import org.apache.zookeeper.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

/**
 * @Author 咕唧
 * @Date 2022/6/29 21:05
 * @Version 1.0
 */
public class ZookeeperAuth {
    //阻塞用的,1代表只需要放行一次就可以了
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    //认证的类型,摘要类型
    private static final String AUTHENTICATION_TYPE = "digest";
    //我们的密码
    private static final String CORRECT_AUTHENTICATION = "123456";

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        //先连接zookeeper
        ZooKeeper zooKeeper=new ZooKeeper(ConnectionUtil.SERVER_ADDRESS, 10000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.err.println("ZookeeperBase01中的方法process 执行了");
                //事件的状态
                Event.KeeperState state = event.getState();
                //事件的类型
                Event.EventType type = event.getType();
                //如果当前的状态是成功
                if (state == Event.KeeperState.SyncConnected) {
                    if (type == Event.EventType.None) {
                        //NONE代表是连接成功'
                        System.err.println("连接zookeeper成功");
                    }
                }
                countDownLatch.countDown();//放行
            }
        });
        //设置了认证信息,第一个参数digest指的是摘要方式,第二个就是密码的字节数组,使用密码创建的节点,在操作的时候需要使用密码
        zooKeeper.addAuthInfo(AUTHENTICATION_TYPE,CORRECT_AUTHENTICATION.getBytes(StandardCharsets.UTF_8));
        countDownLatch.await();//阻塞当前线程

        //创建节点
          zooKeeper.create("/gp11auth", "测试权限数据".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);

        //当我们在第一次使用节点的时候如果是设置了密码的,那么后面使用的时候就需要密码,否则会提示未认证
        byte[] data = zooKeeper.getData("/gp11auth", false, null);
        System.err.println(new String(data));
        //关闭连接
        zooKeeper.close();

    }
}
